package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Category;
import com.gaohe.service.CategoryService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping
    private R list()
    {
        List<Category> list = categoryService.list();
        return R.success(list);
    }
    @GetMapping("/page")
    private R page(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String name)
    {
        Page<Category>page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category>lw = new LambdaQueryWrapper<>();
        lw.like(!StringUtils.isEmpty(name), Category::getName,name);
        lw.orderByDesc(Category::getUpdateTime);
        lw.orderByAsc(Category::getName);
        return R.success(categoryService.page(page1,lw));
    }

//    获取id
    @GetMapping("{id}")
    private R getId(@PathVariable Long id)
    {
        return R.success(categoryService.getById(id));
    }

//    更新数据
    @PutMapping
    private R update(@RequestBody Category category)
    {
        category.setUpdateTime(LocalDateTime.now());
        boolean flag = categoryService.updateById(category);
        return flag?R.success("修改成功"):R.error("修改失败");
    }

//    删除数据
    @DeleteMapping
    private R delete(Long id)
    {
        boolean flag = categoryService.removeById(id);
        return flag?R.success("删除成功"):R.error("删除失败");
    }

}
